import threading
import uuid
import pyautogui
import sys
import mwindow
import datetime
import time
import sched
from pynput.keyboard import Controller, Key, Listener
import win32gui
import win32con
import tkinter as tk  
from tkinter import messagebox 
import jhprocess

def on_press(key):
    # try:
    #     print("正在按压:", format(key.char))
    # except AttributeError:
    #     print("正在按压2:", format(key))
    if(key.char == 'q'):
        return False

def DragMouse(x1:int,y1:int,x2:int,y2:int,sec:int):
    pyautogui.moveTo(x1, y1)
    pyautogui.dragTo(x2, y2, sec, button='left')
    # pyautogui.mouseDown(x1, y1, button='left')
    # pyautogui.moveTo(x2, y2)
    # pyautogui.mouseUp(button='left') 

def ontimer(mainwin,mset : mwindow.MWindowSet,process:jhprocess):
    if mainwin.box.left < -32000:
        print("窗口小于-30000")
        sys.exit(0)
    win = None
    if len(process.priorCheckWinNames) != 0:
        for name in process.priorCheckWinNames:
            win = mset.CheckWindowByName(name)
        process.priorCheckWinNames.clear()
    if win == None:
        win = mset.CheckWindow()
    if win != None:
        print(f'wind.name={win.name}')
        process.OnTimer(mset,win)
    else:
        print(f'wind.name=None')
    loop_monitor()
def loop_monitor():
    timer=threading.Timer(5,ontimer,args=[mainwin,mset,process])
    timer.start()    

def GetMainWnd():
    hwnd = win32gui.FindWindow('Chrome_WidgetWin_0', '几何王国')    
    if hwnd == None:
        return False
    windows = pyautogui.getWindowsWithTitle("几何王国")
    mainwin = None
    for w in windows:
        if w._hWnd == hwnd:
            mainwin = w
            break
    return mainwin

if __name__ == "__main__":
    pyautogui.PAUSE = 2.5
    pyautogui.FAILSAFE = True
    print("start")
    mainwin = GetMainWnd()
    if mainwin == None:
        print("没有找到")
        sys.exit(0)
    mainwin.move(0,0)
    # win32gui.BringWindowToTop(hwnd)
    mainwin.activate()
    if mainwin.box.left < -32000:
        print("窗口小于-30000")
        sys.exit(0)

    process = jhprocess.JHProcess()
    # 初始化窗口集合
    mset = mwindow.MWindowSet((mainwin.box.left,mainwin.box.top,mainwin.box.width,mainwin.box.height),(8,0))
    mset.Load('几何王国.mset')

    # with Listener(on_press=on_press) as listener:
    #     listener.join()        
    loop_monitor()
